package spring.boot.client.client;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import spring.boot.client.codec.InvocationDecoder;
import spring.boot.client.codec.InvocationEncoder;
import spring.boot.client.dispatcher.MessageDispatcher;

import java.util.concurrent.TimeUnit;


@Component
public class NettyClientHandlerInitializer extends ChannelInitializer<Channel> {

    @Autowired
    private MessageDispatcher messageDispatcher;

    @Autowired
    private NettyClientHandler nettyClientHandler;

    @Override
    protected void initChannel(Channel channel) {
        //心跳检测 设定IdleStateHandler心跳检测每四秒进行一次写检测，如果四秒内write()方法未被调用则触发一次userEventTrigger()方法
        //spring.boot.client.client.NettyClientHandler.userEventTriggered
        channel.pipeline().addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));
        // 编码器
        channel.pipeline().addLast(new InvocationEncoder());

        // 解码器
        channel.pipeline().addLast(new InvocationDecoder());

        // 消息分发器
        channel.pipeline().addLast(messageDispatcher);

        // 客户端处理器
        channel.pipeline().addLast(nettyClientHandler);
    }

}
